package msg

import (
	"blog-server/utils/exception"
	"io"
	"io/ioutil"
	"mime/multipart"
	"os"
	"path/filepath"
)

func WriterFile(file *multipart.FileHeader, basePath string, fileName string) error {
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()
	_, err = os.Stat(basePath)
	var newFile *os.File
	if os.IsNotExist(err) {
		err = os.MkdirAll(basePath, os.ModePerm)
		if err != nil {
			return err
		}
	}
	newFile, err = os.Create(filepath.Join(basePath, fileName))
	if err != nil {
		return err
	}
	defer newFile.Close()
	_, err = io.Copy(newFile, src)
	return err
}

func ReadFile(basePath string, fileName string) ([]byte, error) {
	file, err := os.Open(filepath.Join(basePath, fileName))
	if err != nil {
		return nil, exception.NewSysError("读取文件失败")
	}
	defer file.Close()
	all, err := ioutil.ReadAll(file)
	if err != nil {
		return nil, exception.NewSysError("读取文件失败")
	}
	return all, nil
}
